# coding=utf8
import contextlib
import urllib2
from cachetools import cached, TTLCache

try:
    import json
except ImportError:
    import simplejson as json

from elastalert.util import elastalert_logger
# import logging

# reset encoding to utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')

class QywxAuth(object):
    # Add cached to hold access_token（官方有效时间为7200s）
    cache = TTLCache(maxsize=1, ttl=7150)

    @cached(cache)
    def get_token(self, corpid, corpsecret):
        elastalert_logger.info("refresh access_toke")
        get_token_api = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s' % (
            corpid, corpsecret)
        res = urllib2.Request(get_token_api)

        try:
            with contextlib.closing(urllib2.urlopen(res)) as r:
                resp = json.loads(r.read())

                if resp.get('access_token', None):
                    return resp['access_token']
                else:
                    elastalert_logger.error("Get token failed %s:%s" % (resp['errcode'], resp['errmsg']))
                    return False
        except Exception, e:
            elastalert_logger.exception("Get token faied: %s" % (e))
            return False


class QywxMessage(object):
    """
    You need get a instance for push message.
    """

    def _target_format(self, target):
        if isinstance(target, list):
            return '|'.join(target)
        else:
            return target

    def _send_message(self, token=None, agentid=0, msgtype='text',
                      content={}, touser='', toparty='',
                      totag='', safe=0):
        message_body = {
            'touser': self._target_format(touser),
            'toparty': self._target_format(toparty),
            'totag': self._target_format(totag),
            'agentid': agentid,
            'msgtype': msgtype,
            msgtype: content,
            'safe': safe
        }

        if token:
            send_message_api = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s' % token
            res = urllib2.Request(send_message_api)

            with contextlib.closing(
                    urllib2.urlopen(res, json.dumps(message_body,
                                                    ensure_ascii=False))) as r:

                resp = json.loads(r.read())

                if resp.get('errmsg', None) == 'ok':
                    return True
                else:
                    elastalert_logger.error("Send message failed errcode=%s,errmsg=%s,postdata=%s" % (resp['errcode'], resp['errmsg'],resp))
                    return False
        else:
            elastalert_logger.error("Access token not exists!")
            return False

    def send_text(self, token, agentid=0, content='',
                  touser='', toparty='', totag='', safe=0):
        _text_content = {
            'content': content
        }

        return self._send_message(token=token, agentid=agentid, msgtype='text',
                                  content=_text_content, touser=touser,
                                  toparty=toparty, totag=totag, safe=safe)
